//
//  MTInputPhoneController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/4.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

/// 键盘
import IQKeyboardManagerSwift

/// 网络

import Moya
import Result
import RxSwift
import RxCocoa
/// nav
import YPNavigationBarTransition

class MTInputPhoneController: BaseViewController {
    /// MTProvider
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    var titleStr: String = "" {
        didSet {
            titleLabel.text = titleStr
            if titleStr == "请输入绑定的手机号" {
                tipsLabel.text = "温馨提示：请注意查收短信验证码"
            }
        }
    }
    
    //关闭按钮
    lazy var closeImage: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "close-black")
        imgView.contentMode = .center
        imgView.clipsToBounds = true
        imgView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(inputPhoneController(didTapCloseImage:)))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    /// 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "手机验证码登录"
        label.font = PingFangSCSemiboldFont(24)
        label.textColor = UIColor(hex:0x2f2f2f)
        return label
    }()
    
    //提示
    lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.text = "温馨提示：未注册觅颜账户的手机号，登录时将自动注册"
        label.font = PingFangSCRegularFont(10)
        label.textColor = UIColor(hex:0x9b9b9b)
        return label
    }()
    
    //区号
    lazy var areaCodeLabel: UILabel = {
        let label = UILabel()
        label.text = "区号"
        label.font = PingFangSCRegularFont(10)
        label.textColor = UIColor(hex:0x2f2f2f)
        return label
    }()
    
    //+86
    lazy var areaCode: UILabel = {
        let label = createLabel(withText: "+86")
        return label
    }()
    
    //箭头
    lazy var rightIcon: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "icon_right_gary")
        imgView.contentMode = .scaleAspectFill
        imgView.clipsToBounds = true
        imgView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(inputPhoneController(didTapCloseImage:)))
        imgView.addGestureRecognizer(tap)
        return imgView
    }()
    
    //手机号
    lazy var phoneTxt: UITextField = {
        let text = createTextField(withPlaceholder: "手机号")
        text.keyboardType = .numberPad
        return text
    }()
    
    /// 获取短信验证码按钮
    lazy var getSmsCodeButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor(hex:0xe6e6e6)
        btn.setTitle("获取短信验证码", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.addTarget(self, action: #selector(inputPhoneController(getSmsCodeButtonClick:)), for: .touchUpInside)
        return btn
    }()
}

extension MTInputPhoneController {
    override func viewDidLoad() {
        super.viewDidLoad()
        initializeUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = true
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        .backgroundStyleTransparent
    }
    
    override func yp_navigationBarTintColor() -> UIColor! {
        UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigationBackgroundColor() -> UIColor! {
        .clear
    }

    override func yp_navigationBackgroundImage(withIdentifier identifier: AutoreleasingUnsafeMutablePointer<NSString?>!) -> UIImage! {
        return nil
    }

}

extension MTInputPhoneController {
    private func initializeUI() {
        view.backgroundColor = UIColor.theme.background
        view.addSubview(closeImage)
        view.addSubview(titleLabel)
        view.addSubview(tipsLabel)
        view.addSubview(areaCodeLabel)
        view.addSubview(areaCode)
        view.addSubview(rightIcon)
        view.addSubview(phoneTxt)
        view.addSubview(getSmsCodeButton)
        
        closeImage.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(StatusBarHeight+15)
            make.left.equalTo(view).offset(5)
            make.width.height.equalTo(44)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(closeImage.snp.bottom).offset(15)
            make.left.equalTo(view).offset(35)
            make.right.equalTo(view).offset(-35)
        }
        
        tipsLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.left.equalTo(titleLabel)
            make.width.equalTo(250)
        }
        
        areaCodeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(tipsLabel.snp.bottom).offset(40)
            make.left.equalTo(tipsLabel)
            make.width.equalTo(250)
        }
        
        areaCode.snp.makeConstraints { (make) in
            make.top.equalTo(areaCodeLabel.snp.bottom).offset(10)
            make.left.equalTo(areaCodeLabel)
            make.width.equalTo(100)
            make.height.equalTo(40)
        }
        
        rightIcon.snp.makeConstraints { (make) in
            make.centerY.equalTo(areaCode)
            make.left.equalTo(areaCode.snp.right).offset(-10)
            make.width.height.equalTo(15)
        }
        
        
        phoneTxt.snp.makeConstraints { (make) in
            make.top.equalTo(areaCodeLabel.snp.bottom).offset(10)
            make.left.equalTo(rightIcon.snp.right).offset(25)
            make.width.equalTo(180)
            make.height.equalTo(40)
        }
        
        getSmsCodeButton.snp.makeConstraints { (make) in
            make.top.equalTo(phoneTxt.snp.bottom).offset(70)
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
        }
    }
    
    private func createTextField(withPlaceholder placeholder: String) -> UITextField {
        let tf = UITextField()
        tf.font = PingFangSCSemiboldFont(15)
        tf.textColor = UIColor(hex:0x2f2f2f)
        tf.delegate = self
        tf.tintColor = .black
        
        let astr = NSMutableAttributedString(string: placeholder)
        astr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor(hex:0x9b9b9b)], range: NSMakeRange(0, astr.length))
        tf.attributedPlaceholder = astr
        
        let line = UIView()
        line.backgroundColor = UIColor(hex:0xd8d8d8)
        tf.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(tf)
            make.height.equalTo(0.5)
        }
        return tf
    }
    
    private func createLabel(withText text: String) -> UILabel {
        let label = UILabel()
        label.font = PingFangSCSemiboldFont(15)
        label.textColor = UIColor(hex:0x2f2f2f)
        label.text = text
        
        let line = UIView()
        line.backgroundColor = UIColor(hex:0xd8d8d8)
        label.addSubview(line)
        line.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(label)
            make.height.equalTo(0.5)
        }
        return label
    }
}

@objc
extension MTInputPhoneController {
    private func inputPhoneController(didTapCloseImage tap: UITapGestureRecognizer) {
    }
    
    private func inputPhoneController(getSmsCodeButtonClick sender: UIButton) {
        user_provider.rx.originRequest(.sendVerify(parameter: ["mobile":phoneTxt.text ?? ""])).subscribe(onNext: { [weak self] (result, isCache) in
            guard let weakself = self else { return }
            switch result {
                
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200 {
                        let vc: MTVerifyCodeController = MTVerifyCodeController()
                        vc.phone = weakself.phoneTxt.text ?? ""
                        vc.needSetPwd = weakself.titleStr == "请输入绑定的手机号"
                        weakself.navigationController?.pushViewController(vc, animated: true)
                    } else {
                        AlertManager.presentAlertView(message: datas["message"] as? String ?? "")
                    }
                }
                break
                
            case .failure(_):
                AlertManager.presentAlertView(message: "网络错误")
                break
            }
                           
        }).disposed(by: self.disposeBag)

    }
}

extension MTInputPhoneController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let textLength = textField.text?.count
        if textLength ?? 0 == 10 {
            getSmsCodeButton.backgroundColor = UIColor.theme.main
        } else {
            getSmsCodeButton.backgroundColor = UIColor(hex:0xe6e6e6)
        }
        return true
    }
}
